package nil.ed.simulator.request.ui.jfx.manager;

import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Scene;
import javafx.scene.control.MenuBar;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import java.io.IOException;
import java.io.InputStream;

public class FxManager {
    private static Stage stage;
    private static BorderPane root;

    public static void loadScene(String fxml) throws IOException {
        if (stage == null) {
            throw new NullPointerException("stage is null!");
        }
        root = new BorderPane();

        AnchorPane page;
        page = (AnchorPane) loadFXML(fxml);
        root.getChildren().addAll(page);
        Scene scene = new Scene(root);
        stage.setScene(scene);
    }

    public static Object loadFXML(String fxml) throws IOException {
        FXMLLoader loader = new FXMLLoader();
        Object node;
        try (InputStream in = ClassLoader.getSystemResource(fxml).openStream()) {
            loader.setBuilderFactory(new JavaFXBuilderFactory());
            loader.setLocation(ClassLoader.getSystemResource(fxml));
            node = loader.load(in);
        }
        return node;
    }

    public static void setMenuBar(String FXML) {
        if (stage == null) {
            throw new NullPointerException("stage is null!");
        }

        try {
            MenuBar bar = (MenuBar) loadFXML(FXML);
            bar.prefWidthProperty().bind(stage.widthProperty());
            root.setTop(bar);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void gotoMain() {
        try {
            loadScene("ui/fxml/Main.fxml");
            setMenuBar("ui/fxml/MenuBar.fxml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setStage(Stage stage) {
        FxManager.stage = stage;
    }

    public static Stage getStage() {
        return stage;
    }

}
